package leetcode;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-10-30 14:16
 **/
public class LeetCode983 {

    //将引用地址复制一份
    int[] days;
    int[] costs;
    //demo[i]对应从days[i]到结束所需要的最低消费
    Integer[] memo;
    //不同票价对应的无限制旅行天数
    int[] durations = {1, 7, 30};


    public int mincostTickets(int[] days, int[] costs) {
        this.days = days;
        this.costs = costs;
        memo = new Integer[days.length];
        return dp(0);
    }

    //求days[n]到旅行结束的最低花费
    private int dp(int n) {
        //越界直接返回0
        if (n >= days.length) {
            return 0;
        }
        //从days[n]到旅行结束的最低花费已计算过。
        if (memo[n] != null) {
            return memo[n];
        }
        memo[n] = Integer.MAX_VALUE;
        int j = n;
        for (int i = 0; i < 3; i++) {
            while (j < days.length && days[n] + durations[i] > days[j]) {
                j++;
            }
            memo[n] = Math.min(memo[n], dp(j) + costs[i]);
        }
        return memo[n];
    }

}
